let promisify = require('util').promisify
promisify = promisify ? promisify : require('./util').promisify
const fs = require('fs')
const stat = promisify(fs.stat)
const readdir = promisify(fs.readdir)
const handleBars = require('handlebars')
const path = require('path')

const mime = require('../handle/mime')
const press = require('../handle/compress')
const range = require('../handle/range')
const isUseCache = require('../handle/cache')

const tplPath = path.join(__dirname, '../template/dir.tpl')
const source = fs.readFileSync(tplPath)
const template = handleBars.compile(source.toString())


module.exports = async function (req, res, filePath, config) {
	try {
		const root = config.root
		const compress = config.compress
		const stats = await stat(filePath)

		if (stats.isFile()) {


			res.setHeader('Content-Type', `${mime(filePath)};charset=utf-8`)


			if (isUseCache(stats, req, res, config)) {
				res.statusCode = 304
				res.end()
				return
			}

			const {code, start, end} = range(stats.size, req, res)
			res.statusCode = code

			let rs
			switch (code) {
			case 200: {
				rs = fs.createReadStream(filePath)
				break
			}
			case 416: {
				rs = fs.createReadStream(filePath)
				break
			}
			case 206: {
				rs = fs.createReadStream(filePath, {start, end})
				break
			}
			default: {
				rs = fs.createReadStream(filePath)
			}
			}

			if (filePath.match(compress)) {
				rs = press(rs, req, res)
			}
			rs.pipe(res)


		} else if (stats.isDirectory()) {

			const files = await readdir(filePath)

			res.statusCode = 200
			res.setHeader('Content-Type', 'text/html')
			let dir = path.relative(root, filePath)
			dir = dir ? `/${dir}` : ''
			const data = {
				title: path.basename(filePath),
				dir,
				files: files.map(file => {
					return {
						icon: mime(file),
						file
					}
				})
			}
			res.end(template(data))

		}
	} catch (ex) {
		console.error(ex)
		res.statusCode = 404
		res.setHeader('Content-Type', 'text/html')
		res.end('404，资源不存在' + `${ex.toString()}`)

	}


}
